<template>
  <div class="version-container">
    <el-card class="search-card">
      <el-form :model="formInline" label-width="100px" inline>
        <el-form-item label="版本类型">
          <el-select v-model="formInline.verSionType" placeholder="请选择版本类型" clearable style="width: 160px;">
            <el-option label="用户端" value="user" />
            <el-option label="商家端" value="merchant" />
          </el-select>
        </el-form-item>
        <el-form-item label="协议ID">
          <el-input v-model="formInline.ContentId" placeholder="请输入协议ID" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="clear">重置</el-button>
          <el-button type="success" @click="handleAdd">新增协议</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="协议ID" width="100" />
        <el-table-column prop="typeCode" label="协议类型编码" width="150" />
        <el-table-column prop="typeName" label="协议类型名称" width="150" />
        <el-table-column prop="title" label="协议标题" width="200" />
        <el-table-column prop="content" label="协议内容(富文本)" width="250" />
        <el-table-column prop="version" label="协议版本" width="120" />
        <el-table-column prop="effectiveDate" label="生效时间" width="180" />
        <el-table-column prop="isCurrent" label="是否当前版本" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.isCurrent === 1 ? 'success' : 'info'">
              {{ scope.row.isCurrent === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creatorId" label="创建人ID" width="100" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-scroll-wrapper">
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          />
        </div>
      </div>
    </el-card>

    <!-- 查看/编辑弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="600px"
      @close="handleDialogClose"
    >
      <el-form :model="detailData" label-width="120px" ref="formRef">
        <el-form-item label="协议ID">
          <el-input v-model="detailData.id" disabled />
        </el-form-item>
        <el-form-item label="协议类型编码">
          <el-input v-model="detailData.typeCode" :disabled="dialogTitle !== '编辑协议'" />
        </el-form-item>
        <el-form-item label="协议类型名称">
          <el-input v-model="detailData.typeName" :disabled="dialogTitle !== '编辑协议'" />
        </el-form-item>
        <el-form-item label="协议标题">
          <el-input v-model="detailData.title" :disabled="dialogTitle !== '编辑协议'" />
        </el-form-item>
        <el-form-item label="协议版本">
          <el-input v-model="detailData.version" :disabled="dialogTitle !== '编辑协议'" />
        </el-form-item>
        <el-form-item label="生效时间">
          <el-date-picker
            v-model="detailData.effectiveDate"
            type="datetime"
            placeholder="选择生效时间"
            :disabled="dialogTitle !== '编辑协议'"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否当前版本">
          <el-switch
            v-model="detailData.isCurrent"
            :active-value="1"
            :inactive-value="0"
            :disabled="dialogTitle !== '编辑协议'"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="detailData.status"
            :active-value="1"
            :inactive-value="0"
            :disabled="dialogTitle !== '编辑协议'"
          />
        </el-form-item>
        <el-form-item label="创建人ID">
          <el-input v-model="detailData.creatorId" disabled />
        </el-form-item>
        <el-form-item label="协议内容">
          <el-input
            v-if="dialogTitle === '编辑协议'"
            v-model="detailData.content"
            type="textarea"
            :rows="6"
          />
          <div v-else v-html="detailData.content" class="content-preview"></div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button v-if="dialogTitle === '编辑协议'" type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增协议弹窗 -->
    <el-dialog 
      title="新增协议" 
      v-model="addDialogVisible" 
      width="600px"
      @close="handleAddDialogClose"
    >
      <el-form :model="addFormData" label-width="120px" ref="addFormRef" :rules="addFormRules">
        <el-form-item label="协议类型编码" prop="typeCode">
          <el-input v-model="addFormData.typeCode" placeholder="请输入协议类型编码" />
        </el-form-item>
        <el-form-item label="协议类型名称" prop="typeName">
          <el-input v-model="addFormData.typeName" placeholder="请输入协议类型名称" />
        </el-form-item>
        <el-form-item label="协议标题" prop="title">
          <el-input v-model="addFormData.title" placeholder="请输入协议标题" />
        </el-form-item>
        <el-form-item label="协议版本" prop="version">
          <el-select v-model="addFormData.version" placeholder="请选择协议版本" style="width: 100%">
            <el-option label="用户端" value="user" />
            <el-option label="商家端" value="merchant" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" prop="effectiveDate">
          <el-date-picker
            v-model="addFormData.effectiveDate"
            type="datetime"
            placeholder="选择生效时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否当前版本" prop="isCurrent">
          <el-switch
            v-model="addFormData.isCurrent"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="addFormData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="addFormData.sort" :min="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="协议内容" prop="content">
          <el-input
            v-model="addFormData.content"
            type="textarea"
            placeholder="请输入协议内容"
            :rows="6"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm" :loading="addLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { VersionService } from '@/api/versionApi'

// 表单数据
const formInline = ref({
  verSionType: '',
  ContentId: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('查看协议')
const detailData = ref({
  id: undefined,
  typeCode: '',
  typeName: '',
  title: '',
  content: '',
  version: '',
  effectiveDate: '',
  isCurrent: 0,
  status: 0,
  sort: 0,
  creatorId: undefined,
  createTime: '',
  updateTime: ''
})

// 新增协议弹窗相关
const addDialogVisible = ref(false)
const addLoading = ref(false)
const addFormData = ref({
  id: undefined,
  typeCode: '',
  typeName: '',
  title: '',
  content: '',
  version: '',
  effectiveDate: '',
  isCurrent: 0,
  status: 1,
  sort: 0,
  creatorId: undefined,
  createTime: '',
  updateTime: ''
})

const formRef = ref()
const addFormRef = ref()

// 新增协议表单验证规则
const addFormRules = {
  typeCode: [{ required: true, message: '请输入协议类型编码', trigger: 'blur' }],
  typeName: [{ required: true, message: '请输入协议类型名称', trigger: 'blur' }],
  title: [{ required: true, message: '请输入协议标题', trigger: 'blur' }],
  version: [{ required: true, message: '请选择协议版本', trigger: 'change' }],
  effectiveDate: [{ required: true, message: '请选择生效时间', trigger: 'change' }],
  content: [{ required: true, message: '请输入协议内容', trigger: 'blur' }]
}

// 搜索
const search = () => {
  currentPage.value = 1
 getVersionListData()
}

// 清空搜索条件
const clear = () => {
  formInline.value = {
    verSionType: '',
    ContentId: ''
  }
  currentPage.value = 1
 getVersionListData()
}

// 新增协议
const handleAdd = () => {
  // 重置表单数据
  addFormData.value = {
    id: undefined,
    typeCode: '',
    typeName: '',
    title: '',
    content: '',
    version: '',
    effectiveDate: '',
    isCurrent: 0,
    status: 1,
    sort: 0,
    creatorId: undefined,
    createTime: '',
    updateTime: ''
  }
  addDialogVisible.value = true
}

// 查看详情
const handleView = (row: any) => {
  getAgreementDetail(row)
  dialogTitle.value = '查看协议'
  dialogVisible.value = true
}

// 删除协议
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该协议吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    console.log('我执行了')
    try {
      const res = await VersionService.deleteAgreement(row.id)
       console.log('我执行了')
      if (res.code === '200') {
        ElMessage.success('删除成功')
        // 重新加载协议列表
        getVersionListData()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('删除协议失败:', error)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 编辑
const handleEdit = (row: any) => {
  getAgreementDetail(row)
  dialogTitle.value = '编辑协议'
  dialogVisible.value = true
}

// 保存编辑
const submitForm = () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const res = await VersionService.updateAgreement(detailData.value)
        if (res.code === '200') {
          ElMessage.success('编辑协议成功')
          dialogVisible.value = false
          // 重新加载协议列表
          getVersionListData()
        } else {
          ElMessage.error(res.message || '编辑协议失败')
        }
      } catch (error) {
        ElMessage.error('编辑协议失败')
        console.error('编辑协议失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getVersionListData()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getVersionListData()
}

// 获取协议列表
const getVersionListData = () => {
  loading.value = true
  const params = {
    verSionType: formInline.value.verSionType,
    ContentId: formInline.value.ContentId ? parseInt(formInline.value.ContentId) : undefined,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }

  VersionService.getById(params)
    .then((res: any) => {
      if (res.code === '200') {
        console.log('请求发送成功了')
        tableData.value = res.data.list || []
        total.value = res.data.total || 0
      } else {
        ElMessage.error(res.msg || '获取协议列表失败')
      }
      loading.value = false
    })
    .catch(() => {
      loading.value = false
      ElMessage.error('获取协议列表失败')
    })
}

// 获取协议详情
const getAgreementDetail = (row: any) => {
  // 这里可以调用另一个API获取详细信息，或者直接使用行数据
  detailData.value = { ...row }
}

// 弹窗关闭事件
const handleDialogClose = () => {
  // 重置表单验证
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 新增协议弹窗关闭事件
const handleAddDialogClose = () => {
  // 重置表单验证
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 提交新增协议表单
const submitAddForm = () => {
  if (!addFormRef.value) return
  
  addFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      addLoading.value = true
      try {
        const res = await VersionService.addAgreement(addFormData.value)
        if (res.code === '200') {
          ElMessage.success('新增协议成功')
          addDialogVisible.value = false
          // 重新加载协议列表
          getVersionListData()
        } else {
          ElMessage.error(res.message || '新增协议失败')
        }
      } catch (error) {
        ElMessage.error('新增协议失败')
        console.error('新增协议失败:', error)
      } finally {
        addLoading.value = false
      }
    }
  })
}

onMounted(() => {
 getVersionListData()
})
</script>

<style scoped>
.version-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}

/* 分页容器基础样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  min-width: max-content;
  box-sizing: content-box;
}

/* 分页滚动容器增强样式 */
.pagination-scroll-wrapper {
  width: 100%;
  overflow-x: auto !important;
  overflow-y: hidden !important;
  -webkit-overflow-scrolling: touch !important;
  padding-bottom: 15px !important;
  margin: 0 !important;
  position: relative !important;
  z-index: 10 !important;
  flex: none;
  box-sizing: border-box;
}

/* 确保分页滚动容器的父元素不限制其显示 */
.pagination-scroll-wrapper,
.pagination-scroll-wrapper > * {
  transform: translateZ(0);
  will-change: transform;
}

/* 自定义滚动条 */
.pagination-scroll-wrapper::-webkit-scrollbar {
  height: 4px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-track {
  background-color: #f0f0f0;
  border-radius: 2px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 2px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #909399;
}

/* 移动端特殊处理 */
@media (max-width: 768px) {
  .pagination-scroll-wrapper {
    padding-bottom: 20px !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  
  .pagination-container {
    padding-left: 15px !important;
    padding-right: 15px !important;
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  
  /* 简化移动端分页布局，确保所有元素可见 */
  .el-pagination {
    min-width: 100% !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  
  .el-pagination__total {
    min-width: 60px;
    flex-shrink: 0;
  }
  
  .el-pagination__sizes {
    min-width: 100px;
    flex-shrink: 0;
  }
}

.content-preview {
  border: 1px solid #ebeef5;
  min-height: 200px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}
</style>